package com.nh.alarm;

import com.google.gson.Gson;
import com.squareup.okhttp.*;

import java.io.IOException;
import java.util.logging.Logger;

public class HttpClientHelper {
    public static final String CONTENT_TYPE = "application/json; charset=utf-8";
    private static final Logger LOGGER = Logger.getLogger("HttpClientHelper");
    private static OkHttpClient client = new OkHttpClient();

    public static void uploadAlarm(ACSEventAlarm alarm) {
        MediaType JSON = MediaType.parse(CONTENT_TYPE);

        Gson gson = new Gson();
        String josnStr = gson.toJson(alarm);
        LOGGER.info("request body: " + josnStr);
        RequestBody body = RequestBody.create(JSON, josnStr);
        final Request request = new Request.Builder().url(Starter.UPLOAD_URL).post(body).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Request request, IOException e) {
                LOGGER.warning( josnStr + " upload fail:" + e.getMessage());
            }

            public void onResponse(Response response) throws IOException {

                if (response.code() == 200) {
                    LOGGER.info(josnStr + " upload success");
                } else {
                    LOGGER.warning("response code: " + response.code());
                    LOGGER.warning("response upload body: " + response.body().string());
                }

                response.body().close();
            }
        });
    }
}
